﻿var baseTreeUrl = CPWebRootPath + "/api/TreeEngine/GetTreeData";                    //获取树形列表url
var carNumber = $.CPGetQuery("carNumber"); 
var snSensor = $.CPGetQuery("snSensor"); 
var starttime = $.CPGetQuery("leavetime"); 
var endtime = $.CPGetQuery("timenow"); 
var startAddress = $.CPGetQuery("startAddress"); 
var endAddress = $.CPGetQuery("endAddress"); 
var startLon;                    //起点经度
var startLat;                    //起点纬度
var ordersArray;                 //车辆运输订单信息
var passPoint = new Array();     //经过点，数组格式
var timearr, temarr, humarr, temarr2, humarr2;   //时间、温度、湿度
var lushu;                       //百度地图路书

// 百度地图API功能
var map = new BMap.Map("allmap", { enableMapClick: false });  //创建地图实例
var point = new BMap.Point(116.404, 39.915);
//创建点坐标
map.centerAndZoom(point, 6);                                  //初始化地图，设置中心点坐标和地图级别
map.enableScrollWheelZoom(true);                              //允许鼠标滚动轮缩放地图
var myGeo = new BMap.Geocoder();                              //创建地址解析器实例
//添加路况信息控件
var ctrl = new BMapLib.TrafficControl({
    showPanel: false //是否显示路况提示面板
});
map.addControl(ctrl);
ctrl.setAnchor(BMAP_ANCHOR_BOTTOM_RIGHT);
//---------------------------------------------自定义控件---------------------------------------------
// 定义一个控件类,即function
function ZoomControl() {
    // 默认停靠位置和偏移量
    this.defaultAnchor = BMAP_ANCHOR_BOTTOM_RIGHT;
    this.defaultOffset = new BMap.Size(0, 0);
}

// 通过JavaScript的prototype属性继承于BMap.Control
ZoomControl.prototype = new BMap.Control();

// 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
// 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
ZoomControl.prototype.initialize = function (map) {
    // 创建一个DOM元素
    var div = document.createElement("div");
    div.id = "main";                                                                                   //div "main"中显示历史数据的折线图
    div.style.height = "200px";
    div.style.width = "100%";
    div.style.visibility = "collapse";
    // 添加文字说明
    //div.appendChild(document.createTextNode("放大2级"));
    //div.innerHTML = "<img src=\"http://t2.baidu.com/it/u=351117335,2626617599&fm=0&gp=0.jpg\" />"
    // 设置样式
    //div.style.cursor = "pointer";
    //div.style.border = "1px solid gray";
    div.style.background = "black";
    //// 绑定事件
    //div.onclick = function (e) {
    //    //点击一次放大两级
    //    map.setZoom(map.getZoom() + 2);
    //    alert(1);
    //}
    // 添加DOM元素到地图中
    map.getContainer().appendChild(div);
    // 将DOM元素返回
    return div;
}

$(function () {
    $("#allmap").height($(document).height() - 70);
    $("#menu-1").height($(document).height() - 70);
    $("#w-map-silder1").height($(document).height() - 70);

    showHistoryPath();
});


//参数：到当前时间的历史轨迹
function showHistoryPath() {
    map.clearOverlays();
    var myZoomCtrl = new ZoomControl();
    // 添加到地图当中
    map.addControl(myZoomCtrl);
    var div = document.getElementById("main");  //显示历史数据的div           
    div.style.visibility = "visible";
    var inputObj = new Object();
    inputObj.TreeCode = "Tree201811051442280001";
    inputObj.CurUserId = CPCurUserId;
    inputObj.CurUserIden = CPCurUserIden;
    //获取订单信息，得到起点、途径点
    $.ajax({
        type: "POST",
        url: baseTreeUrl + "?CarNumber=" + carNumber,
        data: JSON.stringify(inputObj),
        contentType: 'application/json',
        async: false,
        success: function (result) {  //回调函数，result，返回值  
            $("#roomshow").css('display', 'block');
            if (result.Result == true) {
                carArray = result.DataCol;
                if (carArray != null) {
                    $("#accordion").html("");
                    var thisCount = 0;//用于记录目前读取的是第几辆车
                    $(carArray).each(function (realindex, object) {
                        //获取车辆基本信息
                        var CarInfo = $.parseJSON(object.DataRowJSON);
                        //获取此车运输的订单
                        ordersArray = object.items;
                        var orderCount = ordersArray.length;
                        var firstOrder = ordersArray[0];                            //第一个订单                        
                        startLon = $.parseJSON(firstOrder.DataRowJSON).longitude;   //起点：第一个订单的基地经度
                        startLat = $.parseJSON(firstOrder.DataRowJSON).latitude;    //起点：第一个订单的基地纬度                    
                    });
                }
            }
        }
    });
    //显示规划路径
    var startPoint = new BMap.Point(startLon, startLat);
    //途径点
    $.each(ordersArray, function (oindex, orderItem) {
        if (oindex < ordersArray.length - 1) {
            var orderItemObj = $.parseJSON(orderItem.DataRowJSON);
            passPoint[oindex] = orderItemObj.CustomerState + orderItemObj.CustomerCity + orderItemObj.CustomerDistrict + orderItemObj.CustomerAddress;
        }
    });
    var driving = new BMap.DrivingRoute(map, { renderOptions: { map: map, autoViewport: true } });
    driving.search(startPoint, endAddress, { waypoints: passPoint });//waypoints表示途经点

    //获取GPS数据，显示实际路线
    var hisPoints = new Array();
    var markers = new Array();
    timearr = new Array();
    temarr = new Array();
    humarr = new Array();
    temarr2 = new Array();
    humarr2 = new Array();

    $.ajax({
        type: "GET",
        url: historyDataUrl + "?SN=" + snSensor+"&startTime=" + starttime + "&endTime=" + endtime,      
        dataType: "json",
        error: function (x, e) {
            alert("未查询到车辆信息！");
        },
        async: true,
        beforeSend: function () {
            showMark();
        },
        success: function (result) {
            var json = result;
            var pntlist = json.datalist;//回调函数，result，返回值
            if (pntlist.length != 0) {
                var senlist = pntlist[0].valuelist;    //获取的数据值    
                var unitlist = pntlist[0].fielddim;       //单位数组              
                var sensor;
                $.each(senlist, function (i, tinfo) {
                    sensor = tinfo.fieldvalue;
                    var lng, lat;        //传感器经纬度
                    var temperature1, temperature2, humidity1, humidity2,speed; //传感器实时温度、湿度、速度
                    var unitTem, unitHum, unitSpeed; //单位
                    temperature1 = sensor[0];
                    humidity1 = sensor[1];
                    temperature2 = sensor[2];
                    humidity2 = sensor[3];
                    lat = sensor[4];
                    lng = sensor[5];
                    speed = sensor[8];
                    unitTem = unitlist[0];
                    unitHum = unitlist[1];
                    unitSpeed = unitlist[8];
                    temarr.push(temperature1);
                    humarr.push(humidity1);
                    timearr.push(tinfo.time);
                    temarr2.push(temperature2);
                    humarr2.push(humidity2);
                    var point = new BMap.Point(lng, lat);
                    hisPoints.push(point);
                    var obj = new Object();
                    obj.lng = point.lng;
                    obj.lat = point.lat;
                    obj.html = '<div id="detailinfo" class="w-map-pre" style="top: -160px; right: -140px;"> <div class="w-show-two ">  <div class="w-locon-twott">  <div class="twott-number" style="font-size:12px;">   <p>车牌号</p>    <p>' + carNumber + '</p> </div> <div class="twott-title" style="text-align: left;"> <p>起点：<b>' + startAddress + '</b></p>   </div> <div class="twott-title" style="text-align: left;"><p>终点：<b>' + endAddress + '</b></p>  </div>   </div>  <div class="w-show-treeup">     <ul class="w-jclk2">  <li class="cor-red">  <p>' + temperature1 + unitTem + '</p>  <p>' + temperature2 + unitTem + '</p><p><i class="iconfont  font-30">&#xe605;</i></p>  <p class="cor-gre font-12">温度</p> </li> <li class="cor-purple"> <p>' + humidity1 + unitHum + '</p><p>' + humidity2 + unitHum + '</p> <p><i class="iconfont  font-30 ">&#xe606;</i></p>    <p class="cor-gre font-12">湿度</p></li> <li class="cor-yellow "> <p>' + speed  + '</p> <p>' + unitSpeed + '</p>  <p><i class="iconfont  font-30">&#xe60f;</i></p>  <p class="cor-gre font-12">速度</p>  </li> </ul> </div> <div class="sanjiao"></div> </div> </div>';
                    obj.pauseTime = 0.5;
                    markers.push(obj);
                })
            }
            else {
                alert("未查询到此车辆的历史数据！");
            }
           
        },
        complete: function () {
            hideMark();
            // 实例化一个驾车导航用来生成路线
            map.addOverlay(new BMap.Polyline(hisPoints, { strokeColor: '#111' }));
            map.setViewport(hisPoints);
            if (lushu != null) {
                lushu.pause();
            }
            lushu = new BMapLib.LuShu(map, hisPoints, {
                defaultContent: "",//"从天安门到百度大厦"
                autoView: true,//是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
                icon: new BMap.Icon('../../Plat/Monitor/img/bus.png', new BMap.Size(52, 36), { anchor: new BMap.Size(27, 13) }),
                speed: 8000,
                enableRotation: true,//是否设置marker随着道路的走向进行旋转
                landmarkPois: markers
            });
            setTimeout(function () { lushu.start(); }, 1000);
            setTimeout(function () { lushu.showInfoWindow(); }, 1500);
            showchart();
        }
    });   
}
//显示遮罩层
function showMark() {
    $("#mask").height($(document).height());
    $("#mask").width($(document).width());
    $("#mask").html("<div id='maskText'>数据加载中,请稍后......</div>");
    $("#mask").css("line-height", $(document).height() + "px");
    $("#mask").show();
}
//隐藏遮罩层
function hideMark() {
    $("#mask").hide();
}

//折线图显示历史数据
function showchart() {
    // 路径配置
    require.config({
        paths: {
            echarts: 'http://echarts.baidu.com/build/dist'
        }
    });
    // 使用
    require(
        [
            'echarts',
            'echarts/chart/line' // 使用柱状图就加载bar模块，按需加载
        ],
        function (ec) {
            // 基于准备好的dom，初始化echarts图表
            var myChart = ec.init(document.getElementById('main'));

            var option = {
                title: {
                    text: '',
                    subtext: ''
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['温度曲线1（℃）', '温度曲线2（℃）', "湿度曲线1（%）", "湿度曲线2（%）"],
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: { show: false },
                        dataView: { show: false, readOnly: false },
                        magicType: { show: false, type: ['line', 'bar'] },
                        restore: { show: false },
                        saveAsImage: { show: false }
                    }
                },
                calculable: true,
                xAxis: [
                    {
                        type: 'category',
                        boundaryGap: false,
                        data: timearr
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}'
                        }
                    },
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: function (value) {
                                return value
                            }
                        }
                    },
                ],
                series: [
                    {
                        name: '温度曲线1（℃）',
                        type: 'line',
                        yAxisIndex: 1,
                        data: temarr,
                        markPoint: {
                            data: [
                                { type: 'max', name: '最大值' },
                                { type: 'min', name: '最小值' }
                            ]
                        },
                        //markLine: {
                        //    data: [
                        //        { type: 'average', name: '平均值' }
                        //    ]
                        //},
                        //itemStyle: {
                        //    normal: {
                        //        lineStyle: {
                        //            width: 0.1
                        //        }
                        //    }
                        //}
                    },
                    {
                        name: '温度曲线2（℃）',
                        type: 'line',
                        yAxisIndex: 1,
                        data: temarr2,
                        markPoint: {
                            data: [
                                { type: 'max', name: '最大值' },
                                { type: 'min', name: '最小值' }
                            ]
                        },
                    },
                    {
                        name: '湿度曲线1（%）',
                        type: 'line',
                        data: humarr,
                        markPoint: {
                            data: [
                                { type: 'max', name: '最大值' },
                                { type: 'min', name: '最小值' }
                            ]
                        },
                    },
                    {
                        name: '湿度曲线2（%）',
                        type: 'line',
                        data: humarr2,
                        markPoint: {
                            data: [
                                { type: 'max', name: '最大值' },
                                { type: 'min', name: '最小值' }
                            ]
                        },

                    },
                ]
            };
            // 为echarts对象加载数据 
            myChart.setOption(option);
        }
    );
}